package com.netease.yunxin.kit.chatkit.ui.dialog

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import com.luoxiang.lib_common.bean.NumberBean
import com.luoxiang.lib_common.bean.RestCoinBean
import com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID
import com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA
import com.luoxiang.lib_common.common.Constants.MmkvConst.KEY
import com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN
import com.luoxiang.lib_common.utils.AESUtil
import com.luoxiang.lib_common.utils.MmkvUtil
import com.luoxiang.lib_common.utils.NetUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.netease.yunxin.kit.chatkit.ui.GiftFragment
import com.netease.yunxin.kit.chatkit.ui.R
import com.netease.yunxin.kit.chatkit.ui.bean.GiftMessageBean
import com.netease.yunxin.kit.chatkit.ui.databinding.ChatGiftLayoutBinding
import com.netease.yunxin.kit.chatkit.ui.model.Gift
import com.netease.yunxin.kit.chatkit.ui.model.GiftData
import com.netease.yunxin.kit.common.ui.utils.ToastUtils
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.*

class GiftDialog(
    context: Context,
    private val toUserId: String,
    private val type: Int,
    private val relationId: String

) : BottomPopupView(context) {
    private var num: String? = null

    companion object {
        //todo 当前选择的礼物 默认第一个
        var clickItem: Gift? = null
    }

    var mViewBinding: ChatGiftLayoutBinding? = null
    private var onSendSuccessListener: ((GiftMessageBean) -> Unit)? = null

    override fun getImplLayoutId(): Int = R.layout.chat_gift_layout

    override fun onCreate() {
        super.onCreate()
        val token = MmkvUtil.decodeString(TOKEN) ?: return
        mViewBinding = ChatGiftLayoutBinding.bind(popupImplView)
        mViewBinding?.viewGive?.setOnClickListener(object :
            com.luoxiang.lib_common.utils.CustomClickListener() {
            override fun onSingleClick() {
                clickItem?.id?.let {
                    num = mViewBinding?.textView4?.text.toString()
                    getgiveGift(token, EXTRA, toUserId, type, it, relationId, num?.toInt() ?: 1)
                }
            }

            override fun onFastClick() {

            }
        })

        mViewBinding?.textRecharge?.setOnClickListener {
            LiveEventBus.get<Any>("startWalletActivity").post(null)
            dismiss()
        }
        mViewBinding?.view3?.setOnClickListener {
            //点击选择数量
            XPopup.Builder(context)
                .atView(it) // 依附于所点击的View，内部会自动判断在上方或者下方显示
                .asAttachList(
                    arrayOf("1314  一生一世", "520  我爱你", "66  一切顺利", "10  十全十美", "1  一心一意"),
                    null
                ) { position: Int, text: String? ->

                    mViewBinding?.textView4?.text = when (position) {
                        0 -> "1314"
                        1 -> "520"
                        2 -> "66"
                        3 -> "10"
                        4 -> "1"
                        else -> "1"
                    }
                }
                .show()
        }
        dataSuccess()
    }

    /**
     * 赠送礼物接口
     *
     * @param token
     * @param extra
     * @param toUserId
     * @param type
     * @param giftId
     * @param relationId
     * @param num
     */
    private fun getgiveGift(
        token: String,
        extra: String,
        toUserId: String,
        type: Int,
        giftId: Int,
        relationId: String,
        num: Int
    ) {
        NetUtils.getInstance().getApiService()
            .getgiveGift(token, extra, toUserId, type, giftId, relationId, num)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<NumberBean?> {
                override fun onSubscribe(d: Disposable) {}
                override fun onNext(numberBean: NumberBean?) {
                    val data: String = numberBean?.getData() ?: return
                    var decryptStr: String? = null
                    try {
                        decryptStr =
                            AESUtil.aesDecryptString(data, KEY)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    val gson = Gson()
                    val restCoinBean: RestCoinBean =
                        gson.fromJson(decryptStr, RestCoinBean::class.java)
                    if (restCoinBean.code == 0) {
                        onSendSuccessListener?.invoke(
                            GiftMessageBean(
                                cmd = "gift",
                                gift = com.netease.yunxin.kit.chatkit.ui.bean.Gift(
                                    when (clickItem?.vfx) {
                                        null, "" -> "0"
                                        else -> "1"
                                    },
                                    clickItem?.id.toString(),
                                    clickItem?.name.toString(),
                                    clickItem?.coin.toString(),
                                    "https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/" + clickItem?.icon,
                                    "https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/" + clickItem?.vfx,
                                ),
                                forward = toUserId,
                                fromUserId = MmkvUtil.decodeInt(ACCID).toString(),
                                number = num.toString()
                            )
                        )
                        clickItem?.vfx.let {
                            dismiss()
                            if (it.isNullOrEmpty()) {
                                return@let
                            }
                            XPopup.Builder(context)
                                .moveUpToKeyboard(true)
                                .asCustom(GiftGifDialog(context,
                                    "https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/$it"
                                ))
                                .show()
                            LiveEventBus.get<Any?>("refreshData").post(null)
                        }
                    } else {
                        ToastUtils.showShortToast(context, restCoinBean.msg);
                    }
                }

                override fun onError(e: Throwable) {}
                override fun onComplete() {}

            })
    }

    private fun dataSuccess() {
        val giftData = MmkvUtil.decodeParcelable("GIFT_DATA", GiftData::class.java) ?: return
        mViewBinding?.textCoin?.text = "剩余米币：" + giftData.coin.toString()
        initViewPager2(giftData.gifts)

    }

    private fun initViewPager2(gifts: ArrayList<Gift>?) {
        if (gifts.isNullOrEmpty()) {
            return
        }
        clickItem = gifts[0]
        val giftSplitList: List<List<Gift>> = splitList(gifts, 8) ?: return
        mViewBinding?.viewPager2?.orientation = ViewPager2.ORIENTATION_HORIZONTAL
        mViewBinding?.viewPager2?.offscreenPageLimit = 3
        val fragmentStateAdapter = object :
            FragmentStateAdapter((context as FragmentActivity).supportFragmentManager, lifecycle) {
            override fun getItemCount() = giftSplitList.size

            override fun createFragment(position: Int): Fragment {
                return GiftFragment().apply {
                    arguments = Bundle().apply {
                        putParcelableArrayList("GIFT", arrayListOf<Gift>().apply {
                            addAll(giftSplitList[position])
                        })
                    }
                }
            }
        }
        mViewBinding?.viewPager2?.adapter = fragmentStateAdapter
        mViewBinding?.viewPager2?.let { mViewBinding?.dotsIndicator?.attachTo(it) }
    }

    fun setOnSendSuccess(onSendSuccessListener: (GiftMessageBean) -> Unit) {
        this.onSendSuccessListener = onSendSuccessListener
    }

    private fun <T> splitList(list: List<T>?, len: Int): List<List<T>>? {
        if (list == null || list.isEmpty() || len < 1) {
            return Collections.emptyList()
        }
        val result: MutableList<List<T>> = ArrayList()
        val size = list.size
        val count = (size + len - 1) / len
        for (i in 0 until count) {
            val subList = list.subList(i * len, if ((i + 1) * len > size) size else len * (i + 1))
            result.add(subList)
        }
        return result
    }
}


